
<template>
  <el-container>
    <el-aside>
      <el-header>
        <div><i class="iconfont icon-zuzhijiagou" /> 组织人员管理</div>
      </el-header>
      <el-main>
        <div
          class="custom-tree-container"
          style="background-color:#fefefe;margin-top:10px;    height: calc(100vh - 250px);"
        >
          <div class="block">
            <el-tree
              ref="departTree"
              :data="treeData"
              node-key="Id"
              default-expand-all
              :expand-on-click-node="false"
              :highlight-current="true"
              style="font-size:18px;"
              :indent="0"
              class="tree"
              :props="PerProps"
              @node-click="nodeclick"
            >
              <span
                slot-scope="{ node, data }"
                class="custom-tree-node"
              >
                <span>{{ data.OrgName }}</span>
                <span>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="() => append(node,data)"
                  >
                    <i class="el-icon-circle-plus-outline" />
                  </el-button>
                  <el-button
                    v-if="data.ParentId!='0'"
                    type="text"
                    size="mini"
                    @click.stop="() => edit(node,data)"
                  >
                    <i class="el-icon-edit" />
                  </el-button>
                  <el-button
                    v-if="data.ParentId!='0'"
                    type="text"
                    size="mini"
                    @click.stop="() => remove(node,data)"
                  >
                    <i class="el-icon-delete" />
                  </el-button>
                </span>
              </span>
            </el-tree>

          </div>

          <el-dialog
            :title="textMap[dialogStatus]"
            :visible.sync="dialogFormVisible"
            class="add-department"
            width="40%"
          >
            <el-form
              ref="dataForm"
              :rules="rules"
              :model="temp"
              label-position="left"
              label-width="120px"
              style="width: 100%"
            >
              <div class="split-row">
                <el-form-item
                  label="上级名称"
                  prop="ParentName"
                  class="child"
                >
                  <el-input
                    v-model="temp.ParentName"
                    readonly="readonly"
                  />
                </el-form-item>
              </div>
              <div class="split-row">
                <el-form-item
                  label="部门名称"
                  prop="OrgName"
                  class="child"
                >
                  <el-input v-model="temp.OrgName" />
                </el-form-item>
              </div>
              <!-- <div>
                <el-form-item label="部门主管" prop="ManagerName" class="child">
                  <el-input v-model="temp.ManagerName">
                    <el-button slot="append" icon="el-icon-search" @click="selectPersonClick">选择</el-button>
                  </el-input>
                </el-form-item>
              </div> -->
            </el-form>
            <div
              slot="footer"
              class="dialog-footer"
            >
              <el-button @click="dialogFormVisible = false">关闭</el-button>
              <el-button
                type="primary"
                @click="dialogStatus==='create'?createData():updateData()"
              >保存</el-button>
            </div>
          </el-dialog>
        </div>
      </el-main>
    </el-aside>
    <el-main class="bg-white">
      <el-header>
        <div>
          <i class="iconfont icon-renyuan-" /> 人员管理
          <!-- <el-button
            class="filter-item"
            type="primary"
            size="small"
            style="margin-left:10px"
            icon="el-icon-plus"
            @click="handleUserCreate"
          >新增</el-button> -->
          <!-- <el-button
            class="filter-item"
            type="primary"
            size="small"
            style="margin-left:10px"
            icon="el-icon-upload"
            @click="handleImportPerson"
          >导入人员</el-button> -->
        </div>
        <div>
          <el-input
            v-model="listQuery.SearchKey"
            placeholder="姓名/手机号"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleFilter"
            />
          </el-input>
        </div>

      </el-header>
      <el-main class="main-full-height">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-top:10px;"
        >
          <el-table-column
            label="序号"
            type="index"
            :index="indexMethod"
            width="70px"
            align="center"
          />
          <el-table-column
            label="姓名"
            width="160px"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{ row.UserName }}</span>
              <el-tag
                v-if="row.Id=== temp.Leader"
                class="margin-left-sm"
                type="primary"
                size="mini"
              >主管</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="登录账号"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{ row.Account }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="登录密码"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{ row.Account=='admin'?'admin':'123456789' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="性别"
            align="center"
            width="80"
          >
            <template slot-scope="{row}">
              <span>{{ row.Gender==1 ? "男":row.Gender==2?"女":"未知" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            width="80"
          >
            <template slot-scope="{row}">
              <el-tag
                size="mini"
                :type="row.Status==1 ?'':'danger'"
                effect="light"
              >{{ row.Status==1 ? "启用中":row.Status==2?"已停用":row.Status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="270"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="{row}">
              <el-button
                type="text"
                size="mini"
                @click="handleUserUpdate(row)"
              >修改</el-button>
              <!-- <el-button type="text" size="mini" @click="resetpwd(row)">重置密码</el-button> -->
              <el-button
                v-show="row.Id!== temp.Leader"
                type="text"
                size="mini"
                @click="setManager(row)"
              >设为主管</el-button>
              <!-- <el-button size="mini" type="text" @click="handleSetPermission(row)">基础权限配置</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <el-footer>
        <el-pagination
          :total="total"
          :current-page.sync="listQuery.PageIndex"
          :page-size="20"
          layout="total,prev, pager, next, jumper"
          @current-change="GetUserPageByOrg"
        />
      </el-footer>
      <el-dialog
        :title="textMap[dialogUserStatus]"
        :visible.sync="dialogUserFormVisible"
        class="add-department"
      >
        <el-form
          ref="userDataForm"
          :rules="userrules"
          :model="usertemp"
          label-width="120px"
          style="width: 100%; "
        >
          <div class="split-row">
            <el-form-item
              label="姓名"
              prop="UserName"
              class="child"
            >
              <el-input v-model="usertemp.UserName" />
            </el-form-item>
            <el-form-item
              label="邮箱"
              prop="Email"
              class="child"
            >
              <el-input v-model="usertemp.Email" />
            </el-form-item>
          </div>
          <div class="split-row">
            <el-form-item
              label="登录账号"
              prop="Account"
              class="child"
            >
              <el-input v-model="usertemp.Account" />
            </el-form-item>
            <el-form-item
              label="性别"
              prop="Gender"
              class="child"
            >
              <el-radio-group v-model="usertemp.Gender">
                <el-radio
                  :label="1"
                  checked
                >男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="split-row">
            <el-form-item
              label="部门"
              class="child"
            >
              <p class="for_form_item" @click="handleSelectDepart">
                <el-tag v-for="item in usertemp.UserOrgs" :key="item.Id">{{ item.OrgName }}</el-tag>
              </p>
            </el-form-item>
          </div>
          <div class="split-row">
            <el-form-item
              label="状态"
              prop="Status"
              class="child"
            >
              <el-radio-group v-model="usertemp.Status">
                <el-radio
                  :label="1"
                  checked
                >启用</el-radio>
                <el-radio :label="2">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogUserFormVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="dialogUserStatus==='create'?createUserData():updateUserData()"
          >保存</el-button>
        </div>
      </el-dialog>

    </el-main>
    <ImportPerson
      ref="importPersonRef"
      :department-obj="departmentObj"
      @saveSuccess="handleImportSuccess"
    />
    <selectdepartment ref="selectdepartment" :echo-list="selectedDepartments" @submitSelect="selectedDepart" />
  </el-container>
</template>
<script>
import {
  getDepartment,
  editDepartment,
  setManager,
  DelDepartment
} from '@/api/department/department'
import {
  GetUserPageByOrg,
  addUser,
  editUser,
  GetUserInfoById
} from '@/api/user/user'
import ImportPerson from '@/views/department/importperson'
import selectdepartment from '@/views/components/selectdepartment'
export default {
  filters: {},
  components: { ImportPerson, selectdepartment },
  data() {
    return {
      departmentObj: { Id: '', OrgName: '' },
      departmentId: '',
      treeData: [],
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        Id: '',
        ParentId: '',
        ParentName: '',
        OrgName: '',
        Leader: ''
      },
      checkedUsers: [], // 打开弹窗选择的用户
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        OrgName: [
          { required: true, message: '请填写组织名称', trigger: 'blur' },
          { max: 30, message: '组织名称不能超过30个字', trigger: 'blur' }
        ]
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        OrgId: '',
        PageIndex: 1,
        SearchKey: ''
      },
      unitdata: [],
      orgData: [],
      dialogUserFormVisible: false,
      dialogUserStatus: '',
      usertemp: {
        Id: '',
        BranchId: '',
        UserName: '',
        Account: '',
        Email: '',
        Gender: 1,
        Status: 1,
        Avatar: '',
        UserOrgs: []
      },
      userrules: {
        UserName: [
          { required: true, message: '用户姓名必填', trigger: 'blur' },
          { max: 20, message: '用户姓名不能超过20个字', trigger: 'blur' }
        ],
        Account: [
          { required: true, message: '请填写登录账号', trigger: 'blur' }
        ],
        Status: [
          { required: true, message: '请选择用户状态', trigger: 'change' }
        ]
      },
      orgProps: {
        value: 'Id',
        label: 'OrgName',
        expandTrigger: 'hover',
        multiple: false,
        checkStrictly: true,
        lazy: true,
        lazyLoad(node, resolve) {
          var nodes = []
          if (node && node.data) {
            nodes = node.data.Children
            node.Children = []
          }
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes)
        }
      },
      isDepart: false,
      curruserid: '',
      dialogUserPerVisible: false,
      treePerData: [],
      checkedPerData: [],
      PerProps: {
        value: 'Id',
        children: 'Children',
        label: 'OrgName'
      },
      nodeKey: '',
      selectedDepartments: []
    }
  },
  watch: {
    // 选中的key
    nodeKey(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs.departTree.setCurrentKey(val)
          this.$nextTick(() => {
            document.querySelector('.is-current').firstChild.click()
          })
        })
        this.nodeKey = ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleImportSuccess() {
      this.getList()
    },
    // 导入人员
    handleImportPerson() {
      this.$refs.importPersonRef.handleShow()
    },
    getList() {
      getDepartment().then(res => {
        this.orgData = res.Data
        this.treeData = res.Data
        if (this.temp.Id) {
          this.nodeKey = this.temp.Id
        } else if (res.Data.length > 0) {
          this.nodeKey = res.Data[0].Id
        }
      })
    },

    resetTemp() {
      this.temp = {
        Id: '',
        ParentId: '',
        ParentName: '',
        OrgName: ''
      }
      this.checkedUsers = []
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    append(node, data) {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp = {
        Id: '',
        ParentId: data.Id,
        ParentName: data.OrgName,
        OrgName: ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          editDepartment(this.temp).then(() => {
            this.dialogFormVisible = false
            this.resetTemp()
            this.getList()
          })
        }
      })
    },
    edit(node, data) {
      this.resetTemp()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = {
        Id: data.Id,
        ParentId: node.parent.data.Id,
        ParentName: node.parent.data.OrgName,
        OrgName: data.OrgName
      }
      this.checkedUsers = []
      this.checkedUsers.push({
        Id: data.ManagerId,
        Name: data.ManagerName,
        Type: 2
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          editDepartment(tempData).then(() => {
            this.dialogFormVisible = false
            this.resetTemp()
            this.getList()
          })
        }
      })
    },
    remove(node, data) {
      this.$confirm('确认是否删除该组织?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          DelDepartment(data.Id).then(res => {
            this.$message({
              message: res.Msg,
              type: 'success',
              duration: 5 * 1000
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    nodeclick(obj, node, currnode) {
      this.listQuery.PageIndex = 1
      this.departmentId = obj.Id
      this.temp = {
        Id: obj.Id,
        ParentId: node.parent.data.Id,
        ParentName: node.parent.data.OrgName,
        OrgName: obj.OrgName,
        Leader: obj.Leader
      }
      this.listQuery.OrgId = obj.Id
      this.departmentObj.Id = obj.Id
      this.departmentObj.OrgName = obj.OrgName
      this.GetUserPageByOrg()
    },
    GetUserPageByOrg() {
      this.listLoading = true
      GetUserPageByOrg(this.listQuery).then(response => {
        this.list = response.Data
        this.total = response.TotalItemCount
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    handleFilter() {
      this.listQuery.PageIndex = 1
      this.GetUserPageByOrg()
    },
    resetUserTemp() {
      this.usertemp = {
        Id: '',
        UserName: '',
        Account: '',
        Email: '',
        Gender: 1,
        Status: 1,
        Avatar: '',
        UserOrgs: []
      }
    },
    handleUserCreate() {
      this.resetUserTemp()
      this.dialogUserStatus = 'create'
      this.dialogUserFormVisible = true
      this.usertemp.UserOrgs.push(this.departmentObj)
      this.$nextTick(() => {
        this.$refs['userDataForm'].clearValidate()
      })
    },
    createUserData() {
      this.$refs['userDataForm'].validate(valid => {
        if (valid) {
          addUser(this.usertemp).then(() => {
            this.dialogUserFormVisible = false
            this.resetUserTemp()
            this.GetUserPageByOrg()
          })
        }
      })
    },
    handleUserUpdate(row) {
      GetUserInfoById(row.Id).then(res => {
        this.usertemp = res.Data
      })
      this.dialogUserStatus = 'update'
      this.dialogUserFormVisible = true
      this.$nextTick(() => {
        this.$refs['userDataForm'].clearValidate()
      })
    },
    updateUserData() {
      this.$refs['userDataForm'].validate(valid => {
        if (valid) {
          editUser(this.usertemp).then(() => {
            this.dialogUserFormVisible = false
            this.resetUserTemp()
            this.GetUserPageByOrg()
          })
        }
      })
    },
    handleUserDelete(row, index) {
      this.$confirm.confirm('是否确认删除该用户?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'info',
            message: '模拟删除成功'
          })
          // delUnitUser(row.Id).then(res => {
          //   Message({
          //     message: res.Msg,
          //     type: 'success',
          //     duration: 5 * 1000
          //   })
          //   this.GetUserPageByOrg()
          // })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    resetpwd(row) {
      this.$confirm(
        "是否确认将该用户的登录密码重置为'123456789'",
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          // resetpwd(row.Id).then((res) => {
          //   Message({
          //     message: res.Msg,
          //     type: 'success',
          //     duration: 5 * 1000
          //   })
          // })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 选择主管
    setManager(row) {
      var data = {
        Id: this.temp.Id,
        Leader: row.Id // 部门主管ID
      }
      setManager(data).then(() => {
        this.dialogFormVisible = false
        this.getList()
        this.$message({
          type: 'success',
          message: '设置成功',
          duration: 1000
        })
      })
    },
    indexMethod(index) {
      var PageIndex =
        this.listQuery.PageIndex <= 1 ? 0 : this.listQuery.PageIndex - 1
      return PageIndex * 20 + index + 1
    },
    handleSelectDepart() {
      this.selectedDepartments = this.usertemp.UserOrgs
      this.$refs.selectdepartment.showSelectDepartmentDialog()
    },
    selectedDepart(departs) {
      this.usertemp.UserOrgs = departs
    }
  }
}
</script>

<style>
.el-dialog {
  width: 800px;
}
.app-container {
  margin: 20px 0;
}
/* .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.custom-tree-node button {
  display: none;
}
.custom-tree-node:hover button {
  display: inline-block;
}
.el-tree {
  background: inherit;
}
.custom-tree-container {
  background: #fafafa;
  margin-right: 10px;
  border-radius: 2px;
  padding: 5px;
  border: 1px solid #ebeef5;
}
.el-tree-node__content {
  height: 36px;
} */
</style>
<style scoped>
/* .custom-tree-container /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}
.custom-tree-container /deep/ .el-tree > .el-tree-node:before {
  border-left: none;
}
.tree /deep/ .el-tree-node {
  position: relative;
  padding-left: 16px;
}

.tree /deep/ .el-tree-node__children {
  padding-left: 16px;
}

.tree /deep/ .el-tree-node :last-child:before {
  height: 38px;
}

.tree /deep/ .el-tree > .el-tree-node:before {
  border-left: none;
}

.custom-tree-container /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}

.tree /deep/ .el-tree-node:before {
  content: "";
  left: -4px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

.tree /deep/ .el-tree-node:after {
  content: "";
  left: -4px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

.tree /deep/ .el-tree-node:before {
  border-left: 1px dashed #c3cbd4;
  bottom: 0px;
  height: 100%;
  top: -19px;
  width: 1px;
}

.tree /deep/ .el-tree-node:after {
  border-top: 1px dashed #c3cbd4;
  height: 20px;
  top: 18px;
  width: 24px;
} */
</style>
